<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>todoList</title>
  </head>
  <body>
    <div id="app">
        <h2>商品列表</h2>
        <ul>
            <li v-for="(product,index) in products">
                {{product.name}} - {{product.price}}
                <button @click="addToCart(product)">添加到购物车</button>
            </li>
        </ul>
        <h2>购物车</h2>
        <ul>
            <li v-for="(item,index) in cart">
                {{item.product.name}} - {{item.product.price}} - {{item.quantity}}
            </li>
        </ul>
        <p>总金额:${{totalAmount}}</p>
    </div>
    <script src="vue.js"></script>
    <script>
        var vm = new Vue({
            el:'#app',
            data:{
              products:[//商品列表
                {id:1,name:'Apple15',price:5999},
                {id:2,name:'Mate60Pro',price:6999}
              ],
              //购物车 [{product,quantity}]
              cart:[]
            },
            methods:{
                addToCart(product){
                    //到购物车中查找是否有此商品存在
                    const found = this.cart.find(item=>item.product.id === product.id);
                    if(found){
                        found.quantity++;
                    }else{
                        this.cart.push({product,quantity:1});
                    }
                }
            },
            computed:{
                totalAmount(){
                   return this.cart.reduce((accumulator,item)=>{
                    //累加每个商品的总价，就是用商品的价格乘以商品的数量
                    return accumulator+(item.product.price*item.quantity)
                   },0); 
                }
            }
        });
    </script>
  </body>
</html>